<!-- 编辑器标签栏组件 -->
<template>
  <div v-if="openedNotes && openedNotes.length > 0" class="editor-tabs" :class="{ 'wrap-tabs': settings.editor.wrapTabs }">
    <div class="tabs-container">
      <div
        v-for="note in openedNotes"
        :key="note.fileId"
        class="tab"
        :class="{ active: note.fileId === activeNoteId, modified: note.modified }"
        @click="handleTabClick(note.fileId)"
        @contextmenu.prevent="handleContextMenu($event, note.fileId)"
      >
        <span class="title">{{ note.title }}</span>
        <el-icon class="close-icon" @click.stop="handleCloseTab(note.fileId)">
          <Close />
        </el-icon>
      </div>
    </div>
  </div>

  <!-- 右键菜单 -->
  <el-dropdown
    v-model="contextMenu.visible"
    trigger="contextmenu"
    :show-timeout="50"
    :hide-timeout="150"
    :teleported="true"
    placement="bottom-start"
    :style="contextMenuStyle"
  >
    <span></span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item @click="handleCloseTab(contextMenu.noteId)">
          关闭
        </el-dropdown-item>
        <el-dropdown-item @click="handleCloseOtherTabs(contextMenu.noteId)">
          关闭其他
        </el-dropdown-item>
        <el-dropdown-item @click="handleCloseAllTabs">
          关闭全部
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { storeToRefs } from 'pinia'
import { ElMessageBox } from 'element-plus'
import { Close } from '@element-plus/icons-vue'
import { useEditorStore } from '@/stores/editor'
import { useSettingsStore } from '@/stores/settings'

const editorStore = useEditorStore()
const settingsStore = useSettingsStore()

const { openedNotes, activeNoteId } = storeToRefs(editorStore)
const { settings } = storeToRefs(settingsStore)

// 右键菜单状态
const contextMenu = ref({
  visible: false,
  noteId: '',
  x: 0,
  y: 0
})

const contextMenuStyle = computed(() => ({
  position: 'fixed',
  top: `${contextMenu.value.y}px`,
  left: `${contextMenu.value.x}px`,
  zIndex: 2000
}))

// 处理标签点击
const handleTabClick = (noteId: string) => {
  editorStore.activeNoteId = noteId
}

// 处理标签关闭
const handleCloseTab = async (noteId: string) => {
  try {
    await editorStore.closeNote(noteId)
  } catch (error) {
    if (error.message === 'NOTE_NOT_SAVED') {
      try {
        await ElMessageBox.confirm(
          '当前笔记未保存，是否保存更改？',
          '关闭确认',
          {
            confirmButtonText: '保存',
            cancelButtonText: '不保存',
            type: 'warning',
            distinguishCancelAndClose: true,
            showClose: true
          }
        )
        await editorStore.saveNote(noteId)
        await editorStore.closeNote(noteId, true)
      } catch (action) {
        if (action === 'cancel') {
          await editorStore.closeNote(noteId, true)
        }
      }
    }
  }
}

// 处理右键菜单
const handleContextMenu = (event: MouseEvent, noteId: string) => {
  contextMenu.value = {
    visible: true,
    noteId,
    x: event.clientX,
    y: event.clientY
  }
}

// 关闭其他标签
const handleCloseOtherTabs = async (keepNoteId: string) => {
  try {
    await editorStore.closeOtherNotes(keepNoteId)
  } catch (error) {
    if (error.message === 'NOTE_NOT_SAVED') {
      try {
        await ElMessageBox.confirm(
          '有未保存的笔记，是否保存更改？',
          '关闭确认',
          {
            confirmButtonText: '全部保存',
            cancelButtonText: '不保存',
            type: 'warning',
            distinguishCancelAndClose: true,
            showClose: true
          }
        )
        // 保存所有未保存的笔记
        const unsavedNotes = openedNotes.value.filter(
          note => note.id !== keepNoteId && note.modified
        )
        await Promise.all(unsavedNotes.map(note => editorStore.saveNote(note.id)))
        await editorStore.closeOtherNotes(keepNoteId, true)
      } catch (action) {
        if (action === 'cancel') {
          await editorStore.closeOtherNotes(keepNoteId, true)
        }
      }
    }
  }
}

// 关闭所有标签
const handleCloseAllTabs = async () => {
  try {
    await editorStore.closeAllNotes()
  } catch (error) {
    if (error.message === 'NOTE_NOT_SAVED') {
      try {
        await ElMessageBox.confirm(
          '有未保存的笔记，是否保存更改？',
          '关闭确认',
          {
            confirmButtonText: '全部保存',
            cancelButtonText: '不保存',
            type: 'warning',
            distinguishCancelAndClose: true,
            showClose: true
          }
        )
        // 保存所有未保存的笔记
        const unsavedNotes = openedNotes.value.filter(note => note.modified)
        await Promise.all(unsavedNotes.map(note => editorStore.saveNote(note.id)))
        await editorStore.closeAllNotes(true)
      } catch (action) {
        if (action === 'cancel') {
          await editorStore.closeAllNotes(true)
        }
      }
    }
  }
}
</script>

<style scoped>
.editor-tabs {
  background-color: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-light);
  white-space: nowrap;
  overflow-x: auto;
  height: 40px;
}

.editor-tabs.wrap-tabs {
  height: auto;
  max-height: 80px;
}

.tabs-container {
  display: flex;
  flex-wrap: var(--tabs-wrap, nowrap);
  height: 100%;
}

.wrap-tabs .tabs-container {
  --tabs-wrap: wrap;
}

.tab {
  display: flex;
  align-items: center;
  padding: 0 16px;
  height: 26px;
  border-right: 1px solid var(--el-border-color-light);
  cursor: pointer;
  user-select: none;
  transition: background-color 0.2s;
}

.tab:hover {
  background-color: var(--el-bg-color-page);
}

.tab.active {
  background-color: var(--el-color-primary-light-9);
}

.tab.modified .title::after {
  content: '*';
  margin-left: 4px;
  color: var(--el-color-primary);
}

.title {
  margin-right: 8px;
}

.close-icon {
  font-size: 14px;
  opacity: 0.6;
  transition: opacity 0.2s;
}

.close-icon:hover {
  opacity: 1;
}
</style>
